import React from 'react';
import {Table, Row, Col, Form, Input, Icon, InputNumber, Radio, DatePicker, Select, Upload, Button, Switch, Modal, Popconfirm, Tabs, message} from 'antd';
import moment from 'moment'
import OperatorConstant from "../../utils/OperatorConstant";
import RightBox from "../commons/RightBox";
import RIGHT from "../../utils/RightConstants";

const R = require('ramda');
const TabPane = Tabs.TabPane;
const FormItem = Form.Item;
const dateFormat = 'YYYY-MM-DD';


export default Form.create({wrappedComponentRef: true})(class RelateForex extends React.Component {
    constructor(props) {
        super(props);
        this.initUnrelatorderList(this.props.claim.unrelatorderList);
        this.state = {
            disabled: true,
            type: "",
            releateFlag: false,
            unrelatorderList:[],
            loading: false,
        }
    }

    componentWillReceiveProps(nextProps) {
        if(!R.equals(this.props.claim.unrelatorderList)(nextProps.claim.unrelatorderList)){
            this.initUnrelatorderList(nextProps.claim.unrelatorderList)
        }
    }

    initUnrelatorderList = (dataSource) => {
        dataSource = R.isNil(dataSource) ? {} : dataSource;
        this.state = {unrelatorderList: dataSource}
    }

    handleChangeUnrelatorderAmount = (record, value) => {
        let unrelatorderList = R.clone(this.state.unrelatorderList);
        R.map((row) => {
            if(row.id === record.id){
                row.amount = value;
            }
        }, unrelatorderList)
        this.setState({unrelatorderList: unrelatorderList});
    }


    //外汇关联
    addRelateForex = (record) => {

        this.props.form.validateFields((error, values) =>{
            if(error) return;       

            let amount = record.amount;             //本次关联金额
            let totalamount = record.totalamount;   //订单出口金额
            let gapamount = record.gapamount;       //订单待关联金额

            let dataSource = R.isNil(this.props.dataSource) ? {} : this.props.dataSource;
            let norelateamount =  dataSource.norelateamount;    //外汇待关联金额

            if(R.isNil(norelateamount) || R.isEmpty(norelateamount)){
                message.error("外汇关联金额为空！");
                return;
            }

            if(norelateamount <= 0 ){
                message.error("待关联金额为0，关联失败！");
                return;
            }
       
            if(amount > norelateamount){
                message.error("关联金额大于外汇待关联金额！");
                return;
            }

            //收汇区间
            let strategyList = this.props.claim.strategyList;
            let highprice = "";
            let lowprice  = "";
            let businesstype = "";
            let highpriceRate = "";

            if(R.isNil(strategyList) || R.isEmpty(strategyList)){
                message.error("请先设置收汇区间！");
                return;
            }

            for(let i=0; i< strategyList.length; i++){
                if(strategyList[i].businesstype == "orderSettlement"){
                    businesstype = strategyList[i].businesstype;
                    highpriceRate = strategyList[i].highprice;
                    lowprice = strategyList[i].lowprice;
                    break;
                }
            }   

            if (R.isNil(businesstype) || R.isEmpty(businesstype)) {
                message.error("请先设置收汇区间！");
                return;
            }
            
            if (amount <= 0) {
                message.error("关联金额需大于0！");
                return;
            }

            if (amount == null) {
                message.error("输入金额不能为空！");
                return;
            }

            //最高关联金额=(出口金额*(highpriceRate -1)+待关联金额)
            highprice = totalamount * (highpriceRate -1)+ gapamount;//最高关联金额
            lowprice = gapamount * lowprice;//最低关联金额

            if (amount > highprice ) {
                message.error("关联金额区间错误！建议关联金额小于" + highprice);
                return;
            }

            this.setState({ loading :true});            
            this.state.releateFlag = true;  

            this.props.dispatch({
                type: 'claim/addRelateForex',
                payload: {
                    forxid: this.props.forexId,
                    orderid: record.id,
                    relateamount: amount,
                    exportamount: totalamount,
                    onSuccess:()=>{
                        this.setState({ loading :false});
                        this.props.dispatch({
                            type: 'claim/resetAmoumt',
                        });
                        let data = this.props.dataSource;
                        data.norelateamount = norelateamount-amount;
                        this.props.dispatch({
                            type:'foreignExchangeManage/setDataSource',
                            payload:{
                                data
                            }
                        })
                        },onFail:()=>{
                            this.setState({ loading:false});
                        }
                    }
                });
            })
        }

    //取消关联
    cancelRelateForex = (record) => {
        let amount = record.amount;
        
        if(record.isstated == "1"){
            message.error("已结算的外汇不能取消关联！");
            return;
        }

        this.props.dispatch({
            type: 'claim/cancelRelateForex',
            payload: {
                id: record.id,
                forxid: this.props.forexId,
                orderid: record.orderid,
                relateamount: record.relateamount,
                onSuccess:() =>{
                    let data = this.props.dataSource;
                    data.norelateamount = norelateamount+amount;
                    this.props.dispatch({
                        type:'foreignExchangeManage/setDataSource',
                        payload:{
                            data
                        }
                    })
                }
            }
        });
        this.state.releateFlag = true;
    }

    //确认收齐外汇
    confirmfinishForex = (record) => {

        let orderid = record.orderid;
        let exportamount =  orderid.exportamount;//订单出口金额


        //收汇区间
        let strategyList = this.props.claim.strategyList;
        let highprice = "";
        let lowprice  = "";
        let businesstype = "";

        if(R.isNil(strategyList) || R.isEmpty(strategyList)){
            message.error("请先设置收汇区间！");
            return;
        }

        for(let i=0; i< strategyList.length; i++){
            if(strategyList[i].businesstype == "orderSettlement"){
                businesstype = strategyList[i].businesstype;
                highprice = strategyList[i].highprice;
                lowprice = strategyList[i].lowprice;
                break;
            }
        }

        if (R.isNil(businesstype) || R.isEmpty(businesstype)) {
            message.error("请先设置收汇区间！");
            return;
        }

        let  relatorderList = this.props.claim.relatorderList;

        if(R.isNil(relatorderList) || R.isEmpty(relatorderList)){
            message.error("关联订单为空");
            return;
        };


        let relateamount = 0;

        for(let i=0; i< relatorderList.length; i++){
            if(orderid == relatorderList[i].orderid){
                relateamount += relatorderList[i].relateamount;
            }
        }


        highprice = exportamount * highprice;//最高订单确认收齐外汇金额
        lowprice = exportamount * lowprice;//最低订单确认收齐外汇金额


        if (relateamount > highprice || relateamount < lowprice) {
            message.error("订单总关联金额与出口金额区间错误！区间范围：" + lowprice +"-" + highprice);
            return;
        }


        this.props.dispatch({
            type: 'claim/confirmfinishForex',
            payload: {
                id: record.id,
                forxid: this.props.forexId,
                orderid: record.orderid,
                relateamount: record.relateamount
            }
        });
        this.state.releateFlag = true;
    };


    cancelfinishForex = (record) =>{
        this.props.dispatch({
            type: 'claim/cancelfinishForex',
            payload: {
                id: record.id,
                forxid: this.props.forexId,
                orderId: record.orderid,
                relateamount: record.relateamount
            }
        });
    }

    handleResetFields = () => {
        this.props.form.resetFields();
        this.state.releateFlag = false;
        this.props.dispatch({
            type: 'claim/setUnrelatorderlist',
            payload: {
                list: [],
            }
        });
        this.props.dispatch({
            type: 'claim/setRelatorderlist',
            payload: {
                list: [],
            }
        });
    }

    RelateColumns = [
        {title: '订单号', dataIndex: 'orderno', key: 'orderno', width: '150px'},
        {title: '合同协议号', dataIndex: 'contractno', key: 'contractno'},
        {title: '关联时间', dataIndex: 'createtime', key: 'createtime', width: '150px'},
        {title: '关联人', dataIndex: 'creatorname', key: 'creatorname', width: '150px'},
        {title: '出口金额', dataIndex: 'exportamount', key: 'exportamount'},
        {title: '出口币种', dataIndex: 'currencytype', key: 'currencytype'},
        {title: '结算状态', key: 'isstated', render(record) {
            if("1" == record.isstated){
                return "已结算"
            }else{
                return "未结算"
            }}},
        {
            title: '本次关联金额', key: 'relateamount',

            render: (text, record, index) => {
                let dataSource = R.isNil(this.props.dataSource) ? {} : this.props.dataSource;
                return (
                    <div>
                        <InputNumber disabled={true}  value={record.relateamount}/>
                        {dataSource.recamountunit}
                    </div>
                );

            }
        },
        {
            title: '订单关联金额', key: 'odrelateamount',

            render: (text, record, index) => {
                return (
                    <div>
                        <InputNumber disabled={true}  value={record.odrelateamount}/>
                        {record.currencytype}
                    </div>
                );


            }
        },
        {title: '操作', width: '10    0px', key: 'key_oprator',

            render: (text, record, index) => {

                if(record.foxerstatus == 1){
                    return (<span>已确认外汇收齐
                                <span className="ant-divider"/>
                                <RightBox resource={RIGHT.FOREIGN.FOREIGN_EX_CANCELCONFIRM}>
                                   <Popconfirm placement="leftTop" title={'取消外汇收齐，您可能需要重新走(预)开票、验票流程，是否继续操作?'} onConfirm={this.cancelfinishForex.bind(this, record)} okText="是" cancelText="否">
                                        <a href="#">取消订单外汇收齐</a>
                                   </Popconfirm>
                                </RightBox>
                    </span>);
                }

                return (
                    <span>

                        <RightBox resource={RIGHT.FOREIGN.FOREIGN_ORDER_CANCEL}><Popconfirm placement="leftTop" title={'是否确认取消关联？'} onConfirm={this.cancelRelateForex.bind(this, record)} okText="是" cancelText="否">
                        <a href="#">取消关联</a>
                         </Popconfirm>

                        <span className="ant-divider"/></RightBox>

                        <RightBox resource={RIGHT.FOREIGN.FOREIGN_EX_CONFIRM}><Popconfirm placement="leftTop" title={'确认订单外汇收齐？'} onConfirm={this.confirmfinishForex.bind(this, record)} okText="是" cancelText="否">
                        <a href="#">确认订单外汇收齐</a>
                         </Popconfirm>
</RightBox>
                    </span>
                );

            }
        }
    ];


    unRelateColumns = [
        {title: '订单号', dataIndex: 'orderno', key: 'orderno', width: '150px'},
        {title: '合同协议号', dataIndex: 'contractno', key: 'contractno'},
        {title: '出口币种', dataIndex: 'currencytype', key: 'currencytype'},
        {
            title: '出口金额', key: 'totalamount',

            render: (text, record, index) => {
                return (
                    <div>
                        <InputNumber disabled={true}  value={record.totalamount}/>
                        {record.currencytype}
                    </div>

                );

            }
        },
        {
            title: '已关联金额', key: 'allamount',

            render: (text, record, index) => {
                return (
                    <div>
                        <InputNumber disabled={true}  value={record.allamount}/>
                        {record.currencytype}
                    </div>

                );

            }
        },
        {
            title: '待关联金额', key: 'gapamount',

            render: (text, record, index) => {
                return (
                    <div>
                        <InputNumber disabled={true}  value={record.gapamount}/>
                        {record.currencytype}
                    </div>

                );
            }
        },
        {
            title: '本次关联金额', key: 'amount',

            render: (text, record, index) => {
                let dataSource = R.isNil(this.props.dataSource) ? {} : this.props.dataSource;
                return (
                    <div>
                        <InputNumber disabled={this.props.disabled} min={0} max={99999999999999} value={record.amount}
                                     onChange={this.handleChangeUnrelatorderAmount.bind(this, record)}/>
                        {dataSource.recamountunit}
                    </div>

                );

            }
        },

        {title: '操作', width: '100px', key: 'key_oprator',

            render: (text, record, index) => {
                let dataSource = R.isNil(this.props.dataSource) ? {} : this.props.dataSource;
                let desc = "确定关联外汇"
                if(!R.equals(record.currencytype, dataSource.payeeAmountunit)){
                    desc = "当前出口币种与收汇币种不一致哦"
                }
                return (
                   <RightBox resource={RIGHT.FOREIGN.FOREIGN_EX_RELEVANCE}><span>
                       <Popconfirm title={desc} okText="确定" cancelText="取消" onConfirm={this.addRelateForex.bind(this, record)}>
                            <Button type="primary" size="small"  loading={this.state.loading} disabled={this.props.disabled}>关联</Button>
                      </Popconfirm>
                    </span></RightBox>
                );

            }
        }
    ];


    render() {
        let dataSource = R.isNil(this.props.dataSource) ? {} : this.props.dataSource;

        let relateRagination = {
            showTotal: total => `共 ${total} 条数据`,
            pageSize: this.props.claim.relatorderPage.size,
            total: this.props.claim.relatorderPage.totalRow,
            showSizeChanger: true,
            onShowSizeChange: (current, size) => {
                let newPage = this.props.claim.relatorderPage;
                newPage.size = size;
                newPage.page = 1;
                this.props.dispatch({
                    type: 'claim/getRelatedorderForexList',
                    payload: {
                        forexId: R.isNil(dataSource.id) ? "" : dataSource.id,
                        page: newPage,
                    }
                });
            },
            onChange: (pageNumber, pageSize) => {
                let newPage = this.props.claim.relatorderPage;
                newPage.page = pageNumber;
                this.props.dispatch({
                    type: 'claim/getRelatedorderForexList',
                    payload: {
                        forexId: R.isNil(dataSource.id) ? "" : dataSource.id,
                        page: newPage,
                    }
                });
            }
        }

        let unRelateRagination = {
            showTotal: total => `共 ${total} 条数据`,
            pageSize: this.props.claim.unrelatorderPage.size,
            total: this.props.claim.unrelatorderPage.totalRow,
            showSizeChanger: true,
            onShowSizeChange: (current, size) => {
                let newPage = this.props.claim.unrelatorderPage;
                newPage.size = size;
                newPage.page = 1;
                this.props.dispatch({
                    type: 'claim/getUnrelatorderForexList',
                    payload: {
                        forexId: R.isNil(dataSource.id) ? "" : dataSource.id,
                        page: newPage,
                    }
                });
            },
            onChange: (pageNumber, pageSize) => {
                let newPage = this.props.claim.unrelatorderPage;
                newPage.page = pageNumber;
                this.props.dispatch({
                    type: 'claim/getUnrelatorderForexList',
                    payload: {
                        forexId: R.isNil(dataSource.id) ? "" : dataSource.id,
                        page: newPage,
                    }
                });
            }
        }

        if(this.state.releateFlag == true){
            this.props.dispatch({type: 'foreignExchangeManage/getForexById', payload: {id: this.props.forexId}});
            this.state.releateFlag = false;
        }
        return (
            <div>
                <Tabs>
                    <TabPane tab="已关联订单" key="2">
                        <Row>
                            <Col>
                                <div>
                                    <Table dataSource={this.props.claim.relatorderList} columns={this.RelateColumns} bordered={true} size={'middle'} pagination={relateRagination} scroll={{ x: 900 }}/>
                                </div>
                            </Col>
                        </Row>
                    </TabPane>
                </Tabs>
                <Tabs>
                    <TabPane tab="未关联订单" key="2">
                        <Row>
                            <Col>
                                <div>
                                    <Table rowKey={record => record.id} dataSource={this.state.unrelatorderList} columns={this.unRelateColumns} bordered={true} size={'middle'}
                                           pagination={unRelateRagination} scroll={{ x: 900 }}/>
                                </div>
                            </Col>
                        </Row>
                    </TabPane>
                </Tabs>
            </div>
        );
    }
})


